import json
import logging
import time
import datetime

from django.http import JsonResponse, QueryDict
from django.shortcuts import render

# Create your views here.
from django.views import View

from yunying.extension import OperatingSQL
from yunying.extension import DelOperatingSQL
from yunying.extension import GeneraOperatTubeSQL, UpdateGeneraOperatTubeSQL
from yunying.extension import SomeCollectionSQL, UpdateSomeCollectionSQL
from yunying.extension import YunYingLogSQL
from yunying.extension import GeneraOperatingSQL

from yunying.take_data import sel_operating
from yunying.take_data import sel_generaoperattube, sel_permission
from yunying.take_data import sel_comecollection
from yunying.take_data import sel_some_situation
from database.connection import Link_database
from yunying.take_data import yunying_log
from yunying.take_data import Details_log
from yunying.take_data import generaoperating
from yunying.take_data import sel_all_shop

import os

logger = logging.getLogger(__name__)


def hostname():
    """判断本地与服务器"""
    sys = os.name
    if sys == 'nt':
        hostname = os.getenv('computername')
        return hostname
    elif sys == 'posix':
        host = os.popen('echo $HOSTNAME')
        try:
            hostname = host.read()
            return hostname
        finally:
            host.close()
    else:
        return 'Unkwon hostname'


class OperatingView(View):
    """运营数据视图"""

    def get(self, request):
        page = request.GET.get('page')
        name = request.GET.get('name')
        store_name = request.GET.get('shop_name')
        start_time = request.GET.get('start_time')
        end_time = request.GET.get('end_time')

        a = str(datetime.date.today())  # 当前时间 2018-12-29

        try:
            page = (int(page) - 1) * 20
            if start_time and end_time:
                start_time = int(time.mktime(time.strptime(start_time, '%Y-%m-%d')))
                end_time = int(time.mktime(time.strptime(end_time, '%Y-%m-%d')))
            else:
                start_time = int(time.mktime(time.strptime(a[:-3], '%Y-%m')))  # 一号
                end_time = int(time.mktime(time.strptime(a, '%Y-%m-%d')))  # 当前时间
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 查询
            oper_obj = sel_operating(page, name, store_name, start_time, end_time)
            if store_name:
                query, is_start = oper_obj.sel_store()
                if not is_start:
                    return JsonResponse({"code": 400, 'result': '您无查询 {} 店铺权限'.format(store_name), "data": []})
            else:
                query = oper_obj.sel_name()
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', "data": []})

        try:
            # 数据整理
            data = []
            for i in query:
                a = {
                    "id": i[0],
                    "statdate": time.strftime('%Y-%m-%d', time.localtime(i[1])),
                    "store_name": i[2],
                    "visitors": i[3],
                    "through_visitors": i[4],
                    "drill_visitors": i[5],
                    "sum_turnover": i[6],
                    "brush_single_number": i[7],
                    "brush_single_money": i[8],
                    "pay_buyers_number": i[9],
                    "free_visitors": i[10],
                    "price": i[11],
                    "conversion_rate": i[12],
                    "real_pay_buyers_number": i[13],
                    "real_turnover": i[14],
                    "members_number": i[15],
                    "members_rate": i[16],
                    "refund_money": i[17],
                    "real_money": i[18]
                }
                data.append(a)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '数据错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": data})

    def post(self, request):
        data = request.POST.get('data')

        try:
            data = eval(data)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 存储
            a = OperatingSQL(data)
            if not a:
                return JsonResponse({"code": 400, 'result': '缺少参数', "data": []})
            if a == 2:
                return JsonResponse({"code": 400, 'result': '无此店铺录入权限', "data": []})
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '录入失败', "data": []})

        return JsonResponse({"code": 200, 'result': '录入成功', "data": data})


class DelOperatingView(View):
    """删除运营数据视图"""

    def post(self, request):
        id = request.POST.get('id')

        try:
            id = int(id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 删除
            DelOperatingSQL(id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '删除错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": []})


class GeneraOperatingView(View):
    """自运营店铺管理视图"""

    def get(self, request):
        name = request.GET.get('name')
        try:
            # 查询
            data = generaoperating(name)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询失败', "data": []})

        return JsonResponse({"code": 200, 'result': '查询成功', "data": data})

    def post(self, request):
        user_id = request.POST.get('user')
        shop_name = request.POST.get('shop_name')
        chief_inspector = request.POST.get('chief_inspector')
        director = request.POST.get('director')
        promoters = request.POST.get('promoters')

        try:
            user_id = int(user_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数', "data": []})

        try:
            # 存储
            oper_obj = GeneraOperatingSQL()
            q = oper_obj.storage(user_id, shop_name, chief_inspector, director, promoters)
            if not q:
                return JsonResponse({"code": 400, 'result': '{} 店铺已存在'.format(shop_name), "data": []})
            elif q == 2:
                return JsonResponse({"code": 400, 'result': '您无添加店铺权限', "data": []})
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '创建失败', "data": []})

        return JsonResponse({"code": 200, 'result': '创建成功', "data": []})

    def put(self, request):
        put = request.body.decode()
        try:
            put = json.loads(put)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        shop_name = put.get('shop_name')
        chief_inspector = put.get('chief_inspector')
        director = put.get('director')
        promoters = put.get('promoters')

        try:
            # 修改
            oper_obj = GeneraOperatingSQL()
            oper_obj.modify(shop_name, chief_inspector, director, promoters)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '修改失败', "data": []})

        return JsonResponse({"code": 200, 'result': '分配成功', "data": []})

    def delete(self, request):
        """删除"""
        delete = QueryDict(request.body)
        shop_name = delete.get('shop_name')

        try:
            # 删除
            oper_obj = GeneraOperatingSQL()
            oper_obj.delete_(shop_name)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '删除失败', "data": []})

        return JsonResponse({"code": 200, 'result': '删除成功', "data": []})


class GeneraOperatTubeView(View):
    """代运营项目管理视图"""

    def get(self, request):
        page = request.GET.get('page')
        user_name = request.GET.get('user_name')

        try:
            page = (int(page) - 1) * 20
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 查询
            query = sel_generaoperattube(page, user_name)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', "data": []})

        try:
            # 数据
            data = []
            for i in query:
                a = {
                    "id": i[0],
                    "store_name": i[1],
                    "project_type": i[2],
                    "chief_inspecto": i[3],
                    "director": i[4],
                    "operator": i[5],
                    "start_time": i[6],
                    "end_time": i[7],
                    "account_entry": i[8],
                    "amount_account": i[9],
                    "renewal_time": i[10],
                    "customer_info": i[11],
                    "subscription_info": i[12],
                    "contract_status": i[13],
                    "store_status": i[14],
                    "email": i[15]
                }
                data.append(a)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '数据错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": data})

    def post(self, request):
        user_id = int(request.POST.get('user_id'))
        store_name = request.POST.get('store_name')
        project_type = request.POST.get('project_type')
        chief_inspecto = request.POST.get('chief_inspecto')
        director = request.POST.get('director')
        operator = request.POST.get('operator')
        start_time = request.POST.get('start_time')
        end_time = request.POST.get('end_time')
        account_entry = request.POST.get('account_entry')
        amount_account = request.POST.get('amount_account')

        # 结束时间前推15天就是续签日期
        time_s = datetime.datetime.strptime(end_time, '%Y-%m-%d')
        future_time = time_s - datetime.timedelta(days=15)
        renewal_time = future_time.strftime('%Y-%m-%d')

        customer_info = request.POST.get('customer_info')
        subscription_info = request.POST.get('subscription_info')
        contract_status = request.POST.get('contract_status')
        store_status = request.POST.get('store_status')
        email = request.POST.get('email')

        # 判断用户是否有权限增加店铺（总监，主管可加）
        try:
            per = sel_permission(user_id)
            if per == None:
                return JsonResponse({"code": 400, 'result': '你没有权限新增店铺数据!', "data": []})
        except:
            return JsonResponse({"code": 400, 'result': '存储错误!', "data": []})

        try:
            # 存储
            GeneraOperatTubeSQL(store_name, project_type, chief_inspecto, director, operator, start_time, end_time,
                                account_entry, amount_account, renewal_time, customer_info, subscription_info,
                                contract_status, store_status, email)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '存储错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": []})


class UpdateGeneraOperatTubeView(View):
    """修改代运营管理视图"""

    def post(self, request):
        id = request.POST.get('id')
        store_name = request.POST.get('store_name')
        project_type = request.POST.get('project_type')
        chief_inspecto = request.POST.get('chief_inspecto')
        director = request.POST.get('director')
        operator = request.POST.get('operator')
        start_time = request.POST.get('start_time')
        end_time = request.POST.get('end_time')
        account_entry = request.POST.get('account_entry')
        amount_account = request.POST.get('amount_account')
        # 结束时间前推15天就是续签日期
        time_s = datetime.datetime.strptime(end_time, '%Y-%m-%d')
        future_time = time_s - datetime.timedelta(days=15)
        renewal_time = future_time.strftime('%Y-%m-%d')
        customer_info = request.POST.get('customer_info')
        subscription_info = request.POST.get('subscription_info')
        contract_status = request.POST.get('contract_status')
        store_status = request.POST.get('store_status')
        email = request.POST.get('email')

        try:
            id = int(id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 修改
            UpdateGeneraOperatTubeSQL(id, store_name, project_type, chief_inspecto, director, operator, start_time,
                                      end_time, account_entry, amount_account, renewal_time, customer_info,
                                      subscription_info, contract_status, store_status, email)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '存储错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": []})


class StoreRefund(View):
    """ 代运营店铺退款数据提交 """

    def post(self, request):

        # refund_month = request.POST.get('refund_month')  # 退款月份
        project_type = request.POST.get('project_type')  # 项目类型
        service_amount = request.POST.get('service_amount')  # 服务金额
        shop_name = request.POST.get('shop_name')  # 店铺名称
        contract_time = request.POST.get('contract_time')  # 签约时间
        days = request.POST.get('days')  # 签约天数
        end_date = request.POST.get('end_date')  # 结束时间
        days_completed = request.POST.get('days_completed')  # 已服务天数
        days_remaining = request.POST.get('days_remaining')  # 剩余服务天数
        service_days = request.POST.get('service_days')  # 应服务天数
        service_paid = request.POST.get('service_paid')  # 已付费服务
        residual_service = request.POST.get('residual_service')  # 剩余服务费
        deposit = request.POST.get('deposit')  # 押金
        unpaid_commission = request.POST.get('unpaid_commission')  # 未结提成
        penalty = request.POST.get('penalty')  # 乙方违约金
        refund_amount = request.POST.get('refund_amount')  # 退款金额
        # is_refund = request.POST.get('is_refund')  # 是否退款
        remarks = request.POST.get('remarks')  # 备注
        file = request.FILES.get('file')  # 传入的文件

        times = str(int(time.time()))
        if (hostname()) == 'DESKTOP-424AROC':  # 判断是本地还是服务器
            file_address = './file/' + times + '.pdf'
        else:
            file_address = '/home/OA/FinancialStatements/' + times + '.pdf'

        with open(file_address, 'wb') as f:
            f.write(file.read())
        DB, Cursor = Link_database()
        file_address = 'https://oa.yuetaosem.com:85/FinancialStatements/' + times + '.pdf'
        inset_sql = """ INSERT INTO  store_refund
			(project_type,service_amount, shop_name, contract_time,days,end_date,days_completed,days_remaining,   service_days,service_paid,  residual_service,deposit,unpaid_commission,penalty, refund_amount,remarks,file_url) 
			VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s') """ % (
            project_type, service_amount, shop_name, contract_time, days, end_date, days_completed,
            days_remaining, service_days, service_paid, residual_service, deposit, unpaid_commission, penalty,
            refund_amount, remarks, file_address)
        try:
            Cursor.execute(inset_sql)
            DB.commit()
            code = 200
            result = "录入成功！"
        except:
            code = 400
            result = "操作数据库失败!"

        DB.close()
        Cursor.close()
        return JsonResponse({"code": code, 'result': result, "data": []})


class RefundInquiry(View):
    """ 店铺退款查询 """

    def post(self, request):
        DB, Cursor = Link_database()
        Attendance_Sql = """ select id,refund_month, project_type,service_amount, shop_name, contract_time,days,end_date,days_completed,days_remaining,   service_days,service_paid,  residual_service,deposit,unpaid_commission,penalty, refund_amount,is_refund,remarks,file_url  from store_refund """
        Cursor.execute(Attendance_Sql)
        AttendanceData = Cursor.fetchall()
        AttendanceList = []
        for ad in AttendanceData:
            AttendanceList.append(
                {"id": ad[0], "refund_month": ad[1], "project_type": ad[2], "service_amount": ad[3], "shop_name": ad[4],
                 "contract_time": ad[5], "days": ad[6], "end_date": ad[7], "days_completed": ad[8],
                 "days_remaining": ad[9], "service_days": ad[10], "service_paid": ad[11], "residual_service": ad[12],
                 "eposit": ad[13], "unpaid_commission": ad[14], "penalty": ad[15], "refund_amount": ad[16],
                 "is_refund": ad[17], "remarks": ad[18], "file_url": ad[19]})

        code = 200
        result = "成功！"
        return JsonResponse({"code": code, "result": result, "data": AttendanceList})


class DeleteWithholding(View):
    """ 店铺退款删除 """

    def post(self, request):
        id = int(request.POST.get('id'))  # id
        DB, Cursor = Link_database()
        # 先删除文件
        Attendance_Sql = """ select file_url  from store_refund where id=%d """ % (id)
        Cursor.execute(Attendance_Sql)
        file_url = '/home/OA/FinancialStatements/' + Cursor.fetchone()[0].split('/')[-1]
        os.remove(file_url)

        # 再删除数据
        del_Sql = """ DELETE FROM store_refund WHERE id = %d """ % (id)
        try:
            Cursor.execute(del_Sql)
            DB.commit()
            code = 200
            result = "删除成功!"

        except:
            code = 400
            result = "操作数据库失败!"

        DB.close()
        Cursor.close()
        return JsonResponse({"code": code, "result": result, "data": []})


# class UpdataRefund(View):

# 	""" 修改店铺退款 """ 


# 	def post(self, request):
# 		id = int(request.POST.get('id'))
# 		refund_month = request.POST.get('refund_month') #退款月份
# 		project_type = request.POST.get('project_type') #项目类型
# 		service_amount = request.POST.get('service_amount') #服务金额
# 		shop_name = request.POST.get('shop_name') #店铺名称
# 		contract_time = request.POST.get('contract_time') #签约时间
# 		days = request.POST.get('days') #签约天数
# 		end_date = request.POST.get('end_date') #结束时间
# 		days_completed = request.POST.get('days_completed') #已服务天数
# 		days_remaining = request.POST.get('days_remaining') #剩余服务天数
# 		service_days = request.POST.get('service_days') #应服务天数
# 		service_paid = request.POST.get('service_paid') #已付费服务
# 		residual_service = request.POST.get('residual_service') #剩余服务费
# 		deposit = request.POST.get('deposit') #押金
# 		unpaid_commission = request.POST.get('unpaid_commission') #未结提成
# 		penalty = request.POST.get('penalty') #乙方违约金
# 		refund_amount = request.POST.get('refund_amount') # 退款金额
# 		is_refund = request.POST.get('is_refund') #是否退款
# 		remarks = request.POST.get('remarks') # 备注
# 		file = request.FILES.get('file') #传入的文件
# 		times = str(int(time.time()))
# 		if file: # 需要修改文件
# 			if (hostname()) == 'DESKTOP-424AROC':  # 判断是本地还是服务器
# 				file_address = './file/' + times + '.doc'
# 			else:
# 				file_address = '/home/OA/FinancialStatements/' + times + '.doc'

# 			with open(file_address, 'wb') as f:
# 				f.write(file.read())


# 			DB, Cursor = Link_database()
# 			file_address = 'https://oa.yuetaosem.com:85/FinancialStatements/' + times + '.doc'
# 			Update_Sql = """ UPDATE store_refund SET refund_month = '%s',project_type = '%s', service_amount = '%s',shop_name = '%s',contract_time = '%s',days = '%s', end_date = '%s',days_completed = '%s',days_remaining = '%s',service_days = '%s',	service_paid = '%s',residual_service = '%s',deposit	 = '%s',unpaid_commission = '%s',penalty = '%s',refund_amount = '%s',is_refund = '%s',remarks = '%s',file_url = '%s'  WHERE  id = %d """ % (refund_month, project_type,service_amount, shop_name, contract_time,days,end_date,days_completed,days_remaining,   service_days,service_paid,  residual_service,deposit,unpaid_commission,penalty, refund_amount,is_refund,remarks,file_address,id)
# 			try:
# 				Cursor.execute(Update_Sql)
# 				DB.commit()
# 				code = 200
# 				result = "修改成功！"
# 			except:
# 				code = 400
# 				result = "修改失败，数据库操作失败！"
# 			DB.close()
# 			Cursor.close()
# 			return JsonResponse({"code": code, "result": result, "data": []})
# 		else: # 不需要修改文件

# 			DB, Cursor = Link_database()
# 			Update_Sql = """ UPDATE store_refund SET refund_month = '%s',project_type = '%s', service_amount = '%s',shop_name = '%s',contract_time = '%s',days = '%s', end_date = '%s',days_completed = '%s',days_remaining = '%s',service_days = '%s',	service_paid = '%s',residual_service = '%s',deposit	 = '%s',unpaid_commission = '%s',penalty = '%s',refund_amount = '%s',is_refund = '%s',remarks = '%s' WHERE  id = %d """ % (refund_month, project_type,service_amount, shop_name, contract_time,days,end_date,days_completed,days_remaining,   service_days,service_paid,  residual_service,deposit,unpaid_commission,penalty, refund_amount,is_refund,remarks,id)
# 			try:
# 				Cursor.execute(Update_Sql)
# 				DB.commit()
# 				code = 200
# 				result = "修改成功！"
# 			except:
# 				code = 400
# 				result = "修改失败，数据库操作失败！"
# 			DB.close()
# 			Cursor.close()
# 			return JsonResponse({"code": code, "result": result, "data": []})


class SomeCollectionView(View):
    """代运营提点回款视图"""

    def get(self, request):
        page = request.GET.get('page')

        try:
            page = (int(page) - 1) * 20
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 	# 查询
            query = sel_comecollection(page)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', "data": []})

        try:
            # 数据
            data = []
            for i in query:
                a = {
                    "id": i[0],
                    "project_type": i[1],
                    "clearing_time": i[2],
                    "store_name": i[3],
                    "sales": i[4],
                    "brush_single_money": i[5],
                    "refund_money": i[6],
                    "real_sales": i[7],
                    "investment": i[8],
                    "some": i[9],
                    "commission": i[10],
                    "is_settlement": i[11],
                    "special_note": i[12],
                    "operator": i[13]

                }
                data.append(a)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '数据错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": data})

    def post(self, request):
        project_type = request.POST.get('project_type')
        operator = request.POST.get('operator')
        clearing_time = request.POST.get('clearing_time')
        store_name = request.POST.get('store_name')
        sales = request.POST.get('sales')
        brush_single_money = request.POST.get('brush_single_money')
        refund_money = request.POST.get('refund_money')
        real_sales = request.POST.get('real_sales')
        investment = request.POST.get('investment')
        some = request.POST.get('some')
        commission = request.POST.get('commission')
        is_settlement = request.POST.get('is_settlement')
        special_note = request.POST.get('special_note')
        # director = request.POST.get('director')
        # zhuguan = request.POST.get('zhuguan')
        # commissioner = request.POST.get('commissioner')
        # staff_commission = request.POST.get('staff_commission')
        # commission_note = request.POST.get('commission_note')

        # try:
        # 	# 存储
        SomeCollectionSQL(project_type, operator, clearing_time, store_name, sales, brush_single_money, refund_money,
                          real_sales, investment, some, commission, is_settlement, special_note)
        # except Exception as e:
        # 	logger.error(e)
        # 	return JsonResponse({"code": 400, 'result': '存储错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": []})


class UpdateSomeCollectionView(View):
    """修改代运营提点回款数据视图"""

    def post(self, request):
        id = request.POST.get('id')
        project_type = request.POST.get('project_type')
        operator = request.POST.get('operator')
        clearing_time = request.POST.get('clearing_time')
        store_name = request.POST.get('store_name')
        sales = request.POST.get('sales')
        brush_single_money = request.POST.get('brush_single_money')
        refund_money = request.POST.get('refund_money')
        real_sales = request.POST.get('real_sales')
        investment = request.POST.get('investment')
        some = request.POST.get('some')
        commission = request.POST.get('commission')
        is_settlement = request.POST.get('is_settlement')
        special_note = request.POST.get('special_note')
        # director = request.POST.get('director')
        # zhuguan = request.POST.get('zhuguan')
        # commissioner = request.POST.get('commissioner')
        # staff_commission = request.POST.get('staff_commission')
        # commission_note = request.POST.get('commission_note')

        try:
            id = int(id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 修改
            UpdateSomeCollectionSQL(id, project_type, operator, clearing_time, store_name, sales, brush_single_money,
                                    refund_money, real_sales, investment, some, commission, is_settlement, special_note)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '修改错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": []})


class SomeSituationView(View):
    """代运营管理与提点关联查询视图"""

    def get(self, request):
        page = request.GET.get('page')
        project_type = request.GET.get('project_type')
        store_name = request.GET.get('store_name')

        try:
            page = (int(page) - 1) * 20
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 查询
            query = sel_some_situation(project_type, store_name, page)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', "data": []})

        try:
            # 数据
            data = []
            for i in query:
                a = {
                    "id": i[0],
                    "project_type": i[1],
                    "clearing_time": i[2],
                    "store_name": i[3],
                    "sales": i[4],
                    "brush_single_money": i[5],
                    "refund_money": i[6],
                    "real_sales": i[7],
                    "investment": i[8],
                    "some": i[9],
                    "commission": i[10],
                    "is_settlement": i[11],
                    "special_note": i[12]
                }
                data.append(a)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '数据错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": data})


class OperatingSelf(View):
    """ 自运营店铺名称查找 """

    def post(self, request):
        DB, Cursor = Link_database()
        CheckName_Sql = """ select store_name from operating """
        try:
            Cursor.execute(CheckName_Sql)
            AttendanceData = Cursor.fetchall()
            AttendanceList = []
            for ad in AttendanceData:
                AttendanceList.append(ad[0])
            code = 200
            result = '成功！'
            data = list(set(AttendanceList))  # 去重，重复的店铺
        except:
            code = 400
            result = '失败！'
            data = []
        return JsonResponse({"code": code, 'result': result, "data": data})


class YunYingLogView(View):
    """代运营日志"""

    def get(self, request):
        user_id = request.GET.get('user')
        page = request.GET.get('page')
        start_time = request.GET.get('start_time')
        end_time = request.GET.get('end_time')

        try:
            user_id = int(user_id)
            page = (int(page) - 1) * 20
            if start_time and end_time:
                start_time = int(time.mktime(time.strptime(start_time, '%Y-%m-%d')))
                end_time = int(time.mktime(time.strptime(end_time, '%Y-%m-%d')))
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 查询
            log_obj = yunying_log(user_id, start_time, end_time, page)
            data = log_obj.deal_data()
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": data})

    def post(self, request):
        shop_name = request.POST.get('shop_name')
        sales = request.POST.get('sales')
        brush_money = request.POST.get('brush_money')
        visitors = request.POST.get('visitors')
        conversion_rate = request.POST.get('conversion_rate')
        advertising = request.POST.get('advertising')
        input_rate = request.POST.get('input_rate')
        advertising_rate = request.POST.get('advertising_rate')
        old_customer_rate = request.POST.get('old_customer_rate')
        purchased = request.POST.get('purchased')
        collection_rate = request.POST.get('collection_rate')
        uv_value = request.POST.get('uv_value')
        ztc_sales = request.POST.get('ztc_sales')
        ztc_consumption = request.POST.get('ztc_consumption')
        ztc_roi = request.POST.get('ztc_roi')
        ztc_purchased = request.POST.get('ztc_purchased')
        ztc_collection = request.POST.get('ztc_collection')
        ztc_purchase_cost = request.POST.get('ztc_purchase_cost')
        ztc_click_cost = request.POST.get('ztc_click_cost')
        ztc_uv_value = request.POST.get('ztc_uv_value')
        zz_sales = request.POST.get('zz_sales')
        zz_consumption = request.POST.get('zz_consumption')
        zz_roi = request.POST.get('zz_roi')
        zz_purchased = request.POST.get('zz_purchased')
        zz_collection = request.POST.get('zz_collection')
        zz_purchase_cost = request.POST.get('zz_purchase_cost')
        zz_click_cost = request.POST.get('zz_click_cost')
        zz_uv_value = request.POST.get('zz_uv_value')
        content = request.POST.get('content')
        user_id = request.POST.get('user')

        statdate = int(time.mktime(time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')))

        try:
            user_id = int(user_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': 'id错误', "data": []})

        try:
            # 存储
            YunYingLogSQL(statdate, shop_name, sales, brush_money, visitors, conversion_rate, advertising, input_rate,
                          advertising_rate, old_customer_rate, purchased, collection_rate, uv_value, ztc_sales,
                          ztc_consumption, ztc_roi, ztc_purchased, ztc_collection, ztc_purchase_cost, ztc_click_cost,
                          ztc_uv_value, zz_sales, zz_consumption, zz_roi, zz_purchased, zz_collection, zz_purchase_cost,
                          zz_click_cost, zz_uv_value, content, user_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '存储错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": []})


class DetailsLogView(View):
    """代运营日志详情"""

    def get(self, request):
        id = request.GET.get('id')
        shop_name = request.GET.get('shop_name')
        start_time = request.GET.get('start_time')
        end_time = request.GET.get('end_time')

        a = datetime.datetime.now().strftime('%Y-%m')  # 当前月份

        if not id and not shop_name:
            return JsonResponse({"code": 400, 'result': '参数缺省', "data": []})

        try:
            if id:
                id = int(id)
            if start_time and end_time:
                start_time = int(time.mktime(time.strptime(start_time, '%Y-%m-%d')))
                end_time = int(time.mktime(time.strptime(end_time, '%Y-%m-%d')))
            else:
                start_time = int(time.mktime(time.strptime(a, '%Y-%m')))
                end_time = int(time.time())
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '参数错误', "data": []})

        try:
            # 查询
            log_obj = Details_log(id, shop_name, start_time, end_time)
            data = log_obj.deal_with()
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', "data": []})

        return JsonResponse({"code": 200, 'result': 'OK', "data": data})


class AllShopView(View):
    """查询所有代运营店铺"""

    def get(self, request):
        user_name = request.GET.get('user_name')

        try:
            # 查询
            query = sel_all_shop(user_name)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, 'result': '查询错误', "data": []})

        data = []
        for i in query:
            data.append(i[0])

        return JsonResponse({"code": 200, 'result': 'OK', "data": data})

# class UserLevel(View):

#     ''' 用户等级表 '''

#     def get(self, request):
#         DB, Cursor = Link_database()
#         CheckName_Sql = """ select * from depar_user """
#         Cursor.execute(CheckName_Sql)
#         data = []
#         UserSet = Cursor.fetchall()
#         for user in UserSet:
#             if user[-3] != 0:
#                 data_structure = {
#                         "id":user[-3],
#                         "name" :"",
#                         "value":[]
#                             }
#                 # 姓名查询
#                 CheckName_Sql = """ select name from user where id=%d """ %(data_structure['id'])
#                 Cursor.execute(CheckName_Sql)
#                 name = Cursor.fetchone()[0]
#                 data_structure['name'] = name

#                 # 下级员工查询
#                 for i in data :
#                     CheckName_Sql = """ select tube from depar_user where director=%d """ %(i['id'])
#                     Cursor.execute(CheckName_Sql)
#                     UserSet = Cursor.fetchall()


#                 if data_structure not in data:
#                     data.append(data_structure)
#         print (data)


# AttendanceList = []
# for ad in AttendanceData:
#     if ad[0] != 0:
#         AttendanceList.append(ad[0])
# directorList = list(set(AttendanceList))  # 去重，重复的总监id
# for director in directorList:
# data_structure = {
#             "id":director,
#             "name" :""
#             "value":[]
#                 }

# sql = """ select  tube from depar_user where  director=%d """ %(director)

# return JsonResponse({"code": 200, 'result': "OK", "data": []})


# [{
# "id":60,
# "name" :"潘星星"
# "value":[{"id":56,
#     "name":"方航"
#     "value":[{"id":54,
#               "name":"王阳"，
#               "value":[]
#               }]

#      }]
# }]
